<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="deliveryDate"
                label="送货日期"
                :rules="[{ required: true, message: '请选择送货日期' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ADatePicker v-model="form.deliveryDate" placeholder="送货日期" class="w100" />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem
                field="customerId"
                label="所属客户"
                :rules="[{ required: true, message: '请选择所属客户' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect v-model="form.customerId" placeholder="所属客户" allow-search allow-create>
                  <AOption
                    v-for="(item, index) in companyList"
                    :key="index"
                    :label="item.customerName"
                    :value="item.customerId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="isInclTax" label="含税">
                <ASelect v-model="form.isInclTax" placeholder="是否含税" allow-search>
                  <AOption label="是" :value="1"></AOption>
                  <AOption label="否" :value="0"></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="deliveryMethod" label="配送方式">
                <ASelect v-model="form.deliveryMethod" allow-search placeholder="配送方式">
                  <AOption label="自提" value="自提"></AOption>
                  <AOption label="包送" value="包送"></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="sellersId" label="业务员">
                <ASelect v-model="form.sellersId" allow-search allow-clear placeholder="业务员">
                  <AOption
                    v-for="(item, index) in employeeList"
                    :key="index"
                    :label="item.employeeName"
                    :value="item.employeeId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="transportCarNo" label="运输车辆">
                <AInput v-model="form.transportCarNo" placeholder="运输车牌号" />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="invoiceStatus" label="开票情况">
                <ASelect v-model="form.invoiceStatus" allow-search placeholder="开票情况">
                  <AOption label="未开票" value="未开票"></AOption>
                  <AOption label="已提交" value="已提交"></AOption>
                  <AOption label="已开票" value="已开票"></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="24">
              <AFormItem field="attachFiles" label="附件">
                <upload v-model:attach-files="attachFiles"></upload>
              </AFormItem>
            </ACol>
            <ACol :span="24">
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
              </AFormItem>
            </ACol>
            <ACol :span="24">
              <ACard
                v-for="(item, index) in form.detailList"
                :key="index"
                class="card-container"
                size="small"
              >
                <template #extra>
                  <ALink @click="editProduct('add')">增加产品</ALink>
                  <ALink
                    v-if="!item.outboundStatus && form.detailList.length > 1"
                    @click="editProduct('del', index)"
                  >
                    删除产品
                  </ALink>
                </template>
                <ARow :gutter="10">
                  <ACol :span="12">
                    <AFormItem
                      :field="`detailList[${index}].materialStockId`"
                      label="产品名称"
                      :rules="[{ required: true, message: '请输入产品名称' }]"
                      :validate-trigger="['change', 'input', 'blur']"
                    >
                      <ASelect
                        v-if="!item.outboundStatus"
                        v-model="item.materialStockId"
                        placeholder="产品名称"
                        allow-search
                        @change="changeEvent('material', item)"
                      >
                        <AOption
                          v-for="(stockItem, index) in stockList"
                          :key="index"
                          :label="stockItem.materialName"
                          :value="stockItem.materialStockId"
                        >
                          <div class="w100 erp-row-center-between">
                            <div>{{ stockItem.materialName }}</div>
                            <ATag v-if="stockItem.spec" color="blue">
                              {{ stockItem.spec }}
                            </ATag>
                          </div>
                        </AOption>
                      </ASelect>
                      <div v-else>{{ item.materialName }}</div>
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="spec" label="规格型号">
                      {{ item.spec }}
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="unit" label="单位">
                      {{ item.unit }}
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="qty" label="数量">
                      <AInputNumber
                        v-if="!item.outboundStatus"
                        v-model="item.qty"
                        model-event="input"
                        placeholder="数量"
                        hide-button
                        :precision="0"
                        :step="1"
                        @change="inputEvent('unitPrice', item)"
                      />
                      <div v-else>{{ item.qty }}</div>
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="unitPrice" label="单价">
                      <AInputNumber
                        v-if="!item.outboundStatus"
                        v-model="item.unitPrice"
                        model-event="input"
                        placeholder="单价"
                        hide-button
                        :precision="4"
                        :step="1"
                        @change="inputEvent('unitPrice', item)"
                      />
                      <div v-else>{{ item.unitPrice }}</div>
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="amt" label="金额">
                      <div>{{ `¥${formatPrice(item.amt || 0, 4)}` }}</div>
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="orderCode" label="销售订单">
                      <AInput v-model="item.orderCode" placeholder="销售订单" />
                    </AFormItem>
                  </ACol>
                  <ACol :span="12">
                    <AFormItem field="remark" label="备注">
                      <AInput v-model="item.remark" placeholder="备注" />
                    </AFormItem>
                  </ACol>
                </ARow>
              </ACard>
            </ACol>
          </ARow>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue'
import { CustomerResItem, editCustomer, getCustomerAllList } from '@renderer/api/company'
import {
  DeliveryReq,
  DeliveryResItem,
  editDelivery,
  getDeliveryDetail
} from '@renderer/api/logisticsDep'
import { formatPrice } from '@renderer/utils/mixins'
import { getStockAllList, StockResItem } from '@renderer/api/warehouseManage'
import { deleteNullObject } from '@renderer/utils/data-processing'
import { differenceBy, isEmpty } from 'lodash-es'
import upload from '@renderer/components/upload/index.vue'
import { useMenuState } from '@renderer/store'
import { EmployeeResItem, getEmployeeAllList } from '@renderer/api/employee'
import { FileListType, getArrayItemType } from '@renderer/types/global'
import { batchDelUploadFile } from '@renderer/api/common'
import { decimalRound } from '@renderer/utils/mixins'

interface Props {
  [key: string]: any
  checkData?: Partial<DeliveryResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const attachFiles = ref<FileListType[]>([])
const form = ref<DeliveryReq>({
  customerId: '',
  customerName: '',
  deliveryDate: '',
  isInclTax: 0,
  transportCarNo: '',
  invoiceStatus: '',
  remark: '',
  detailList: [
    {
      deliveryOrderDetailId: '',
      deliveryOrderCode: '',
      materialStockId: '',
      qty: 0,
      unitPrice: 0,
      amt: 0,
      spec: '',
      unit: '',
      materialName: '',
      materialCode: '',
      materialDesc: '',
      fluteType: '',
      crimpLine: '',
      outboundStatus: 0,
      deliveryOrderId: '',
      remark: '',
      orderCode: ''
    }
  ],
  fileList: [],
  deliveryMethod: '',
  sellersId: '',
  sellersName: ''
})
const companyList = ref<CustomerResItem[]>([])
const stockList = ref<StockResItem[]>([])
const menuParam = useMenuState()
const employeeList = ref<EmployeeResItem[]>([])

// 获取员工列表
const getEmployee = () => {
  getEmployeeAllList({}).then((res) => {
    employeeList.value = res.data.list
  })
}
// 获取产品列表
const getStockList = () => {
  getStockAllList({ materialName: '', materialType: 2 }).then((res) => {
    stockList.value = res.data.list
  })
}

// 获取客户列表
const getCompanyList = () => {
  getCustomerAllList({
    customerName: '',
    taxNo: '',
    contactName: ''
  }).then((res) => {
    companyList.value = res.data.list
  })
}

// 获取详情
const getDetail = () => {
  getDeliveryDetail({ deliveryOrderId: props.checkData.deliveryOrderId! }).then((res) => {
    form.value = res.data
    attachFiles.value = form.value.fileList ? [...form.value.fileList] : []
    if (isEmpty(form.value.detailList)) {
      form.value.detailList = [
        {
          deliveryOrderDetailId: '',
          deliveryOrderCode: '',
          materialStockId: '',
          qty: 0,
          unitPrice: 0,
          amt: 0,
          spec: '',
          unit: '',
          materialName: '',
          materialCode: '',
          materialDesc: '',
          fluteType: '',
          crimpLine: '',
          outboundStatus: 0,
          deliveryOrderId: '',
          remark: '',
          orderCode: ''
        }
      ]
    }
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate(async (errors: any) => {
        if (!errors) {
          const delFile = differenceBy(form.value.fileList, attachFiles.value)
          const delFileIds = delFile.map((item) => item.fileId)
          form.value.fileList = attachFiles.value
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.deliveryOrderId = undefined
          }
          if (!isEmpty(delFileIds)) {
            await batchDelUploadFile({ fileIdList: delFileIds })
          }
          const temp = companyList.value.find((item) => item.customerId === form.value.customerId)
          if (!temp) {
            Modal.warning({
              title: '警告',
              content: '当前客户不存在，是否新增当前客户？',
              okText: '确认',
              cancelText: '取消',
              simple: false,
              hideCancel: false,
              maskClosable: false,
              closable: false,
              onOk: () => {
                editCustomer({ customerName: form.value.customerId }).then((res) => {
                  editDelivery(
                    deleteNullObject({ ...form.value, customerId: res.data as string })
                  ).then(() => {
                    Message.success(
                      (attrs.title as string).includes('新增') ? '新增成功' : '修改成功'
                    )
                    modalEvent('cancel')
                    emit('reload')
                  })
                })
              },
              onCancel: () => {}
            })
          } else {
            editDelivery(deleteNullObject(form.value)).then(() => {
              Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
              modalEvent('cancel')
              emit('reload')
            })
          }
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        customerId: '',
        customerName: '',
        deliveryDate: '',
        isInclTax: 0,
        sellersName: '',
        sellersId: '',
        transportCarNo: '',
        invoiceStatus: '',
        remark: '',
        detailList: [
          {
            deliveryOrderDetailId: '',
            deliveryOrderId: '',
            deliveryOrderCode: '',
            materialStockId: '',
            qty: 0,
            unitPrice: 0,
            amt: 0,
            spec: '',
            unit: '',
            materialName: '',
            materialCode: '',
            materialDesc: '',
            fluteType: '',
            crimpLine: '',
            outboundStatus: 0,
            remark: '',
            orderCode: ''
          }
        ],
        fileList: [],
        deliveryMethod: ''
      }
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCompanyList()
      getStockList()
      getEmployee()
      if (attrs.title === '修改') {
        getDetail()
      }

      break
    case 'cancel':
      formRef.value.resetFields()
      emit('update:visible', false)
      menuParam.switchEditStatus(false)
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        deliveryOrderDetailId: '',
        deliveryOrderId: '',
        deliveryOrderCode: '',
        materialStockId: '',
        qty: 0,
        unitPrice: 0,
        amt: 0,
        spec: '',
        unit: '',
        materialName: '',
        materialCode: '',
        materialDesc: '',
        fluteType: '',
        crimpLine: '',
        outboundStatus: 0,
        remark: '',
        orderCode: ''
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}

const inputEvent = (
  type: 'qty' | 'unitPrice',
  paramsItem: getArrayItemType<DeliveryReq['detailList']>
) => {
  switch (type) {
    case 'qty':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    case 'unitPrice':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    default:
      break
  }
}

const changeEvent = (type: string, detailInfo: getArrayItemType<DeliveryReq['detailList']>) => {
  switch (type) {
    case 'material':
      {
        const temp = stockList.value.find(
          (item) => item.materialStockId === detailInfo.materialStockId
        )
        if (temp) {
          detailInfo.spec = temp.spec!
          detailInfo.unit = temp.unit!
          detailInfo.unitPrice = temp.unitPrice!
        }
      }
      break

    default:
      break
  }
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}

:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
